import React, { createContext, useContext, useReducer, ReactNode } from 'react';

export type GameMode = 'single' | 'couple' | 'none';
export type GameState = 'start' | 'playing' | 'paused' | 'over';

interface GameContextState {
  mode: GameMode;
  state: GameState;
  score: {
    player1: number;
    player2: number;
  };
  highScore: number;
}

type GameAction =
  | { type: 'SET_MODE'; payload: GameMode }
  | { type: 'SET_STATE'; payload: GameState }
  | { type: 'UPDATE_SCORE'; payload: { player: 1 | 2; score: number } }
  | { type: 'UPDATE_HIGH_SCORE'; payload: number }
  | { type: 'RESET_GAME' };

const initialState: GameContextState = {
  mode: 'none',
  state: 'start',
  score: {
    player1: 0,
    player2: 0,
  },
  highScore: 0,
};

const gameReducer = (state: GameContextState, action: GameAction): GameContextState => {
  switch (action.type) {
    case 'SET_MODE':
      return { ...state, mode: action.payload };
    case 'SET_STATE':
      return { ...state, state: action.payload };
    case 'UPDATE_SCORE':
      return {
        ...state,
        score: {
          ...state.score,
          [`player${action.payload.player}`]: action.payload.score,
        },
      };
    case 'UPDATE_HIGH_SCORE':
      return { ...state, highScore: action.payload };
    case 'RESET_GAME':
      return {
        ...initialState,
        highScore: state.highScore,
      };
    default:
      return state;
  }
};

const GameContext = createContext<{
  state: GameContextState;
  dispatch: React.Dispatch<GameAction>;
} | null>(null);

export const GameProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(gameReducer, initialState);

  return (
    <GameContext.Provider value={{ state, dispatch }}>
      {children}
    </GameContext.Provider>
  );
};

export const useGame = () => {
  const context = useContext(GameContext);
  if (!context) {
    throw new Error('useGame must be used within a GameProvider');
  }
  return context;
}; 